<template>
  <div class="my-practices">
    <div class="header">
      <h2>我的实践活动</h2>
      <div class="view-toggle">
        <el-radio-group v-model="viewMode" size="small">
          <el-radio-button label="card">
            <el-icon><Grid /></el-icon> 卡片
          </el-radio-button>
          <el-radio-button label="table">
            <el-icon><List /></el-icon> 列表
          </el-radio-button>
        </el-radio-group>
      </div>
    </div>
    
    <div v-if="loading" class="loading">
      <el-icon class="is-loading"><Loading /></el-icon>
      加载中...
    </div>
    
    <div v-if="error" class="error">
      {{ error }}
    </div>
    
    <!-- 卡片视图 -->
    <div v-if="!loading && !error && viewMode === 'card'" class="card-view">
      <el-row :gutter="20">
        <el-col v-for="practice in practices" :key="practice.practiceId" :xs="24" :sm="12" :md="8" :lg="6">
          <el-card class="practice-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>{{ practice.practiceName || '未命名实践' }}</span>
              </div>
            </template>
            <div class="card-content">
              <div class="info-item">
                <el-icon><User /></el-icon>
                <span>{{ practice.teacherName || '未知教师' }}</span>
              </div>
              <div class="info-item">
                <el-icon><Notebook /></el-icon>
                <span>{{ practice.courseName || '未关联课程' }}</span>
              </div>
              <div class="info-item">
                <el-icon><Clock /></el-icon>
                <span>{{ formatDate(practice.startTime) }} 至 {{ formatDate(practice.endTime) }}</span>
              </div>
            </div>
            <div class="card-actions">
              <el-button type="primary" size="small" @click="showPracticeDetail(practice.practiceId)">
                详情
              </el-button>
              <el-button type="danger" size="small" @click="quitPractice(practice.practiceId)">
                退出
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 列表视图 -->
    <el-table v-if="!loading && !error && viewMode === 'table'" :data="practices" style="width: 100%">
      <el-table-column prop="practiceName" label="实践名称" width="180" />
      <el-table-column prop="teacherName" label="指导教师" width="120" />
      <el-table-column prop="courseName" label="关联课程" width="120" />
      <el-table-column prop="startTime" label="开始时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button 
            type="primary" 
            size="small"
            @click="showPracticeDetail(row.practiceId)"
          >
            详情
          </el-button>
          <el-button 
            type="danger" 
            size="small"
            @click="quitPractice(row.practiceId)"
          >
            退出
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 实践详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="实践详情" width="50%">
      <div v-if="currentPracticeDetail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="实践名称">{{ currentPracticeDetail.name }}</el-descriptions-item>
          <el-descriptions-item label="关联课程">{{ currentPracticeDetail.courseName }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ formatDate(currentPracticeDetail.startTime) }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ formatDate(currentPracticeDetail.endTime) }}</el-descriptions-item>
          <el-descriptions-item label="描述">{{ currentPracticeDetail.description || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div v-else class="loading">
        <el-icon class="is-loading"><Loading /></el-icon>
        加载详情中...
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { Grid, List, User, Notebook, Clock, Loading } from '@element-plus/icons-vue'

const authStore = useAuthStore()
const practices = ref([])
const loading = ref(false)
const error = ref(null)
const detailDialogVisible = ref(false)
const currentPracticeDetail = ref(null)
const detailLoading = ref(false)
const viewMode = ref('card') // 默认卡片视图

// 显示实践详情
const showPracticeDetail = async (practiceId) => {
  try {
    detailLoading.value = true
    detailDialogVisible.value = true
    currentPracticeDetail.value = null
    
    const response = await fetch(`/api/student/practices/${practiceId}`)
    if (!response.ok) throw new Error('获取实践详情失败')
    
    currentPracticeDetail.value = await response.json()
  } catch (err) {
    ElMessage.error(err.message)
    detailDialogVisible.value = false
  } finally {
    detailLoading.value = false
  }
}

// 获取学生ID
const getStudentId = async () => {
  const userId = authStore.userId
  if (!userId) {
    error.value = '用户未登录'
    return null
  }

  try {
    loading.value = true
    error.value = null
    
    const response = await fetch(`/api/student/id/by-user/${userId}`)
    if (!response.ok) throw new Error('获取学生ID失败')
    
    const data = await response.json()
    const studentId = data?.data || data?.result || data
    
    if (!studentId) {
      throw new Error('未获取到有效学生ID')
    }
    
    return studentId
  } catch (err) {
    error.value = err.message
    ElMessage.error(error.value)
    return null
  } finally {
    loading.value = false
  }
}

// 加载我的实践列表
const loadMyPractices = async () => {
  const studentId = await getStudentId()
  if (!studentId) return

  try {
    loading.value = true
    error.value = null
    
    const response = await fetch(`/api/student/practices/my-practices?studentId=${studentId}`)
    if (!response.ok) throw new Error('加载我的实践失败')
    
    practices.value = await response.json()
  } catch (err) {
    error.value = err.message
    ElMessage.error(error.value)
  } finally {
    loading.value = false
  }
}

// 退出实践
const quitPractice = async (practiceId) => {
  try {
    const confirmed = await ElMessageBox.confirm(
      '确定要退出该实践活动吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    if (confirmed) {
      const studentId = await getStudentId()
      if (!studentId) return

      loading.value = true
      const response = await fetch(`/api/student/practices/${practiceId}/quit?studentId=${studentId}`, {
        method: 'DELETE'
      })
      
      if (!response.ok) throw new Error('退出实践失败')
      
      ElMessage.success('退出实践成功')
      await loadMyPractices()
    }
  } catch (err) {
    if (err !== 'cancel') {
      error.value = err.message
      ElMessage.error(error.value)
    }
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})
}

// 获取状态标签类型
const getStatusType = (status) => {
  switch(status) {
    case 0: return 'info'
    case 1: return 'success'
    case 2: return 'warning'
    default: return ''
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch(status) {
    case 0: return '未开始'
    case 1: return '进行中'
    case 2: return '已结束'
    default: return '未知'
  }
}

onMounted(() => {
  loadMyPractices()
})
</script>

<style scoped>
.my-practices {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.view-toggle {
  margin-left: auto;
}

.loading, .error {
  margin: 20px 0;
  text-align: center;
}

.error {
  color: red;
}

/* 卡片视图样式 */
.card-view {
  margin-top: 20px;
}

.practice-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.practice-card:hover {
  transform: translateY(-5px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-content {
  padding: 10px 0;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.info-item .el-icon {
  margin-right: 8px;
  color: var(--el-color-primary);
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.card-actions .el-button {
  margin-left: 10px;
}
</style>